
/* global App */

var MembersView = View.extend(MembersView = {
    init: function() {
        this._super();
        this.search_mode = false;
        this.configure();
    },
    configure: function() {
        this.configureInfiniteScroll();
        this.configureTable();
        this.configureToolbar();
        this.configureProfileEditor();
    },
    
    configureTable: function() {
        var self = this;

        $("#checkall").change(function() {
            if ($(this).is(":checked")) {
                $("#table_view tbody input:checkbox").attr("checked", "checked");
            }

            else {
                $("#table_view tbody input:checkbox").removeAttr("checked");
            }
        });

        $(".sort_menu").click(function(e) {
            e.preventDefault();

            $('.sort_btn i').removeClass().addClass($(this).find('i').attr('class'));
            $("#member_list_sort_order").val($(this).data('sort-order'));

            var url = $("#member_list_url").val() + "/" + $("#member_list_category_id").val() + "/" + $("#member_list_sort_order").val();
            $("#table-view").data('url', url);

            self.reloadTableView();

            //$.cookie('table_view_url', $(this).attr("href"), {path: window.location.href, expires: 7});
        });

        /*var list_url = $.cookie('table_view_url');
         
         if( list_url ) {
         $("#table-view").data('url', list_url);
         $("#list-table-content").update_url(list_url);
         
         if( list_url.indexOf("alpha") > -1 ) {
         $('.sort_btn i').removeClass().addClass("fa fa-list-ol");
         }
         else {
         $('.sort_btn i').removeClass().addClass("fa fa-arrow-down");
         }
         }*/
    },
    /** Infinite Scroll**/
    configureInfiniteScroll: function() {
        var self = this;

        $("#list-table-content").ajax_scroll({
            buffer: 10,
            load_limit: 50,
            total_pages: $("#total_members").val(),
            url: $("#table-view").data('url'),
            callback: function(response) {
                $("#list-table tbody").append(response);
                self.reconfigureTableView();
            }
        });
    },
    configureProfileEditor: function() {

        var self = this;

        $("#edit_btn").click(function() {
            var member_id = self.getSelectedMemberId();
            var url = $(this).data('url') + "/" + $("#member_list_category_id").val() + "/" + member_id;

            self._loadProfileEditor(url, true);
        });

        $("#profile_editor #save-changes").click(function() {
            $("#profile_editor #profile-form").submit();
        });
    },
    /**
     * 
     * @returns {void}
     */
    configureToolbar: function() {
        var self = this;

        $("#category_select").bind('changed', function() {
            var selectedItem = $(this).select('selectedItem');
            self.loadMemberList(selectedItem.value);

            $("#member_list_category_id").val(selectedItem.value);
        });

        $("#add_btn").click(function(e) {
            e.preventDefault();

            self.setProfileViewTitle($(this).attr('title'));
            self.showEditButtons(false);

            var url = $(this).attr('href') + "/" + $(this).data('category-id');
            self._loadProfileEditor(url);
        });

        $("#delete-menu").click(function(e) {
            e.preventDefault();

            var url = $(this).attr('href');
            var member_ids = self.getCheckedMemberIds();

            if (member_ids.length == 0) {
                alert("Please select members to delete and try again");
                return;
            }

            confirm("Continuing with this action will delete the selected members.", function() {
                $.post(url, {member_ids: member_ids}, function() {
                    $("#list-table tbody tr input:checked").each(function() {
                        $(this).parents("tr").remove();
                    });
                });
            });
        });

        $("#change-category").click(function(e) {
            e.preventDefault();

            var member_ids = self.getCheckedMemberIds();

            if (member_ids.length == 0) {
                alert("No members selected. Please select members in order to continue");
                return;
            }
            
            var url = $("#change-category").attr('href');

            $.get(url, function(html) {
                $("#ajaxModal").html(html);

                $("#ajaxModal #change_category_btn").click(function(e) {
                    e.preventDefault();
                    self.changeCategory();
                });

                $("#ajaxModal").modal();
            });
        });

        $("#send-sms").click(function(e) {
            e.preventDefault();

            var numbers = self.getCheckedMemberNumbers();

            if (numbers.length == 0) {
                alert("No members selected. Please select members with phone numbers in order to continue");
                return;
            }
            
            App.notify('sendSmsMessage', numbers);
            
            /*var url = $("#send-sms").attr('href');

            $.get(url, function(html) {
                $("#ajaxModal").html(html);

                $("#ajaxModal #send_message_btn").click(function(e) {
                    e.preventDefault();
                    self.sendInstantMessage();
                });

                $("#ajaxModal").modal();
            });*/
        });


        $("#member-search-form").submit(function(e) {
            e.preventDefault();

            self.loadMemberList($("#member-search-form #member-search-type").val(), $("#member-search-form #member-search").val());
        });

        $("#clear-btn").click(function() {
            $("#member-search-form #member-search").val('');
            $("#list-table tbody").html('');
            $("#list-table-content").reset_scroll();
        });

        $("body").on('changed', '#category_select', function(event) {
            var select = event.target;
            var label = $(select).select('selectedItem')['addLabel'];
            var category_id = $(select).select('selectedItem')['value'];

            $("#add_btn").html("<i class='fa fa-plus'></i> Add " + label);
            $("#add_btn").attr('title', 'Adding ' + label);
            $("#add_btn").data('category-id', category_id);
            
            $("#member-search-type").val(category_id);
        });
    },
    
    changeCategory: function() {
        var self = this;
        
        var url = $("#change_category_btn").attr("href");
        var member_ids = self.getCheckedMemberIds();

        if (member_ids.length == 0) {
            alert("Please select members to upgrade to full membership status");
            return;
        }
        
        var category_id = $("#category_list").val();
        
        if( category_id == $("#add_btn").data('category-id') ) {
            alert("Please select a category different from the current membership category");
            return;
        }

        confirm('Are you sure you want to change the membership category for the selected members', function() {
            $.post(url, {
                member_ids: member_ids, 
                category_id: category_id
            }, function(res) {
                if (res.status == 'success') {
                    $("#ajaxModal").modal('hide');
                    
                    $("#list-table tbody tr input:checked").each(function() {
                        $(this).parents("tr").remove();
                    });
                }
                
                else {
                    alert(res.message);
                }
            }, 'json');
        });
    },
    
    loadMemberList: function(organisation_member_category_id, term) {
        var self = this;

        $("#table-view #list-table tbody").html("Loading ...");

        $("#list-table-content").stop_scroll();

        var sort_order = $("#member_list_sort_order").val();
        var url = $("#member_list_url").val() + "/" + organisation_member_category_id + "/" + sort_order;
        var params = {
            text: term
        };

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            success: function(data) {
                $("#table-view #list-table tbody").html(data);
                self.reconfigureTableView();
            },
            error: function(xhr) {
                alert('Failed to load list of members for selected category');
            }
        });
    },
    /**
     * 
     */
    _loadProfileEditor: function(url, editing) {

        var self = this;
        self.editing = editing;

        self.showAjaxLoadOverlay(true);

        $.ajax({
            url: url,
            type: 'post',
            success: function(data) {
                self.prepareEditor(data);
            },
            error: function(xhr) {
                alert("Failed to load profile editor. Please try again");
            }
        });
    },
    prepareEditor: function(data) {
        var self = this;
        
        self.showEditButtons(false);

        $("#profile-view #profile_view_pane").show().find(".content").html(data);

        $("#profile-form #cancel-btn").click(function() {
            confirm("You are about to cancel the member information update process. Do you want to continue?", function() {
                self.reloadSelectedProfile();
            });
        });

        $(".datepicker-input").each(function() {
            $(this).datepicker();
        });
        
        self.configurePhoneNumbers();
        self.configureEmailAddress();
        self.configureEditorForVisitors();
        self.configureEditorForFamilyInfo();

        var iv = new ImagesView();
        iv.quickUploader({
            selector: '#upload-btn',
            target_view: "#profile-image",
            params: {
                member_id: $("#profile_form #member_id").val()
            },
            callback: function(image) {
                $("#member_image_id").val(image.id);
                $("#image_id").val(image.id);
            }
        });

        $("#profile-form").submit(function(e) {
            e.preventDefault();

            var url = this.action;
            var query = $(this).serialize();

            self.showAjaxLoadOverlay(true);

            $.ajax({
                url: url,
                data: query,
                type: 'post',
                dataType: 'json',
                success: function(data) {
                    $("#profile_editor").modal('hide');

                    if (self.editing) {
                        self.reloadSelectedProfile();
                    }
                    else {
                        self.reloadTableView();
                    }
                },
                error: function(xhr) {
                    alert("Failed To Save Changes For Information Entered. Please Try Again");
                    self.showAjaxLoadOverlay(false);
                }
            });

            return false;
        });

        self.showAjaxLoadOverlay(false);
    },
    
    configurePhoneNumbers: function() {
            
        function addPhoneNumber() {
            var $tmpl = "<div class='input-group m-b-xs'>" +
                            '<div class="input-group-btn phone_type">' +
                                '<button type="button" class="btn btn-white btn-sm dropdown-toggle" data-toggle="dropdown">' +
                                    '<span class="dropdown-label" data-placeholder="Please select"><i class="fa fa-mobile"></i> </span>'+
                                    '<span class="caret"></span>' +
                                '</button>' +
                                '<ul class="dropdown-menu dropdown-select">' +
                                    '<li class="active"><a href="#"><input type="radio" name="Member[MemberPhoneNumber][{i}][type]" value="mobile" /><span class="html"><i class="fa fa-mobile"></i></span> Mobile</a></li>' +
                                    '<li><a href="#"><input type="radio" name="Member[MemberPhoneNumber][{i}][type]" value="home" /><span class="html"><i class="fa fa-home"></i></span> Home</a></li>' +
                                    '<li><a href="#"><input type="radio" name="Member[MemberPhoneNumber][{i}][type]" value="office" /><span class="html"><i class="fa fa-phone"></i></span> Office</a></li>' +
                                '</ul>' +
                            '</div>' +
                            "<input type='text' name='Member[MemberPhoneNumber][{i}][number]' class='form-control input-sm phone_number' value=''/>" + 
                            "<span class='input-group-addon remove_phone_number'>" +
                                "<a href='#'><i class='fa fa-minus'></i></a>" +
                            "</span>" +
                        "</div>";
            
            var ins = $tmpl.replace(/{i}/g, $(".phone_number").length);
            $("#phone_numbers_block").append(ins);
            
            $(".phone_number").intlTelInput({
                defaultCountry: 'gh'
            });
        }
        
        function removePhoneNumber(id, callback) {
            var url = $("#remove_phone_number_url").val();
            
            $.ajax({
                url: url,
                data: {member_id: $("#member_id").val(), id: id},
                type: 'post',
                dataType: 'json',
                success: function( response ) {
                    if( callback ) {
                        callback();
                    }
                },
                error: function( xhr ) {
                    console.log(xhr.responseText);
                }
            });
        }
        
        $("#add_phone_number").click(function() {
            addPhoneNumber();
        });
        
        $(".phone_number").intlTelInput({
            defaultCountry: 'gh'
        });
        
        $(document).on('click', '.remove_phone_number', function() {
            var inp_parent = $(this).parents('.input-group');
            if( inp_parent.find('.phone_number_id').length == 0 ) {
                inp_parent.hide('slow', function() {
                    inp_parent.remove();
                    
                    if( $(".phone_number").length == 0 ) {
                        addPhoneNumber();
                    }
                });
            }
            
            else {
                confirm('This will permanently delete this phone number record. Are you sure you want to continue?', function() {
                    var id = inp_parent.find('.phone_number_id').val();
                    inp_parent.hide('slow');
                    
                    removePhoneNumber(id, function() {
                        inp_parent.remove();
                        
                        if( $(".phone_number").length == 0 ) {
                            addPhoneNumber();
                        }
                    });
                });
            }
        });
    },
    
    configureEmailAddress: function() {
            
        function addEmail() {
            var $tmpl = "<div class='input-group m-b-xs'>" +
                            "<input type='text' name='Member[MemberEmail][{i}][email]' class='form-control input-sm email' value=''/>" + 
                            "<span class='input-group-addon remove_email'>" +
                                "<a href='#'><i class='fa fa-minus'></i></a>" +
                            "</span>" +
                        "</div>";
            
            var ins = $tmpl.replace("{i}", $(".email").length);
            $("#emails_block").append(ins);
        }
        
        function removeEmail(id, callback) {
            var url = $("#remove_email_url").val();
            
            $.ajax({
                url: url,
                data: {member_id: $("#member_id").val(), id: id},
                type: 'post',
                dataType: 'json',
                success: function( response ) {
                    if( callback ) {
                        callback();
                    }
                },
                error: function( xhr ) {
                    console.log(xhr.responseText);
                }
            });
        }
        
        $("#add_email").click(function() {
            addEmail();
        });
        
        $(document).on('click', '.remove_email', function() {
            var inp_parent = $(this).parents('.input-group');
            if( inp_parent.find('.email_id').length == 0 ) {
                inp_parent.hide('slow', function() {
                    inp_parent.remove();
                    
                    if( $(".email").length == 0 ) {
                        addEmail();
                    }
                });
            }
            
            else {
                confirm('This will permanently delete this email record. Are you sure you want to continue?', function() {
                    var id = inp_parent.find('.email_id').val();
                    inp_parent.hide('slow');
                    
                    removeEmail(id, function() {
                        inp_parent.remove();
                        
                        if( $(".email").length == 0 ) {
                            addEmail();
                        }
                    });
                });
            }
        });
    },
    
    configureEditorForVisitors: function() {

        var member_status = $("#profile_view_pane #org_member_status").val();

        if (member_status == 'visitor') {
            $("#profile_view_pane #org_id_row").hide();
            $("#profile_view_pane #extra_profile_info").hide();
        }
    },
    configureEditorForFamilyInfo: function() {
        var self = this;

        $('#add_child_btn').click(function() {
            var i = $(".child_block").length;

            var template = "<div class='child_block'>" +
                    "<input type='text' class='form-control input-sm input-s name' placeholder='Name' name='Member[MemberChild][0][name]' /> " +
                    "<input type='text' class='form-control input-sm input-s-sm datepicker-input' data-date-format='yyyy-mm-dd' placeholder='Birth Date' name='Member[MemberChild][0][dob]' /> " +
                    "<select class='form-control input-sm input-s-sm' name='Member[MemberChild][0][gender]'>" +
                    "<option value=''>Gender</option>" +
                    "<option value='male'>Male</option>" +
                    "<option value='female'>Female</option>" +
                    "</select> " +
                    "<label class='input-sm input-s-sm'>" +
                    "<input type='hidden' name='Member[MemberChild][0][is_alive]' value='1' />" +
                    "<input type='checkbox' name='Member[MemberChild][0][is_alive]' value='0' /> " +
                    "<span>Deceased</span>" +
                    "</label> " +
                    "<button type='button' class='btn btn-xs btn-danger remove_child'>" +
                    "<i class='fa fa-times'></i>" +
                    "</button>" +
                    "<input type='hidden' name='Member[MemberChild][0][member_id]' value='{member_id}' />" +
                    "<input type='hidden' class='child_id' name='Member[MemberChild][0][id]' value='' />" +
                    "</div>";

            template = template.replace(/\[0\]/g, "[" + i + "]")
                    .replace("{member_id}", $("#member_id").val());

            $("#children_block").append(template);

            $(".datepicker-input").each(function() {
                $(this).datepicker();
            });

            $('.child_block:last-child').find(".name").focus();
        });

        $("#children_block").on('click', '.remove_child', function() {
            var child_id = $(this).parents(".child_block").find('.child_id').val();

            if (child_id) {
                var block = $(this);

                confirm("Remove information about this child?", function() {
                    block.parents(".child_block").hide('fast', function() {
                        $(this).remove();

                        if (child_id) {
                            self.removeChild(child_id);
                        }
                    });
                });
            }
        });
    },
    removeChild: function(child_id) {
        var url = $("#remove_child_url").val();
        var params = {
            child_id: child_id,
            member_id: $("#member_id").val()
        };

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(response) {
                console.log(response);
            },
            error: function(xhr) {
                console.log(xhr.responseText)
            }
        });
    },
    /**
     * 
     * @returns {int}
     */
    getSelectedMemberId: function() {
        var member_id = null;

        if ($("#list-table tbody tr.selected").length > 0) {
            member_id = $("#list-table tbody tr.selected").data('member-id');
        }

        return member_id;
    },
    
    getSelectedOrgMemberId: function() {
        var org_member_id = null;

        if ($("#list-table tbody tr.selected").length > 0) {
            org_member_id = $("#list-table tbody tr.selected").data('org-member-id');
        }
        return org_member_id;
    },
    
    getCheckedMemberIds: function() {
        var member_ids = [];

        $("#list-table tbody tr :checked").each(function() {
            member_ids.push($(this).val());
        });

        return member_ids;
    },
    
    getCheckedMemberNumbers: function() {
        var numbers = [];

        $("#list-table tbody tr :checked").each(function() {
            var number = $(this).parents('tr.member_list_row').attr('data-member-phone-number');
            
            if( number ) {
                numbers.push(number);
            }
        });

        return numbers;
    },
    
    /**
     * 
     */
    reconfigureTableView: function() {
        var self = this;

        $("#list-table tbody tr").click(function() {
            $("#list-table tbody tr").removeClass("selected");
            $("#list-table tbody tr input:checkbox").removeAttr("checked");

            $(this).addClass("selected").find("input:checkbox").attr("checked", true);

            var url = $(this).data('url');

            self.showAjaxLoadOverlay(true);

            $.get(url, function(data) {
                self.showSelectedProfile(data);
            });
        });

        if ($("#list-table tbody tr.selected").length == 0) {
            $("#list-table tbody tr:first").click();
        }

        $("#list-table tbody tr input:checkbox").click(function(e) {
            e.stopPropagation();
        });
    },
    reloadTableView: function() {
        $("#list-table tbody").html("");
        $("#list-table-content").update_url($("#table-view").data('url'));
        $("#list-table-content").start_scroll();
        $("#list-table-content").reset_scroll();
    },
    /**
     * Force refresh selected profile
     * 
     * @returns {void}
     */
    reloadSelectedProfile: function() {
        $("#list-table tbody tr.selected").click();
    },
    /**
     * 
     */
    showSelectedProfile: function(profile_data) {

        $("#profile-view #editor_view").hide();
        $("#profile-view #profile_view_pane").show().find(".content").html(profile_data);

        var tr = $("#list-table tbody tr.selected");
        this.setProfileViewTitle(tr.find(".member_name").text() + " - " + tr.find(".org_number").text());
        this.showEditButtons();

        var iv = new ImagesView();
        iv.quickUploader({
            selector: '#change-img-btn',
            target_view: "#image-box",
            url: $("#change-img-btn").data('url'),
            params: {
                member_id: $("#change-img-btn").data('member-id')
            }
        });

        this.showAjaxLoadOverlay(false);
    },
    /**
     * 
     */
    setProfileViewTitle: function(title) {
        if (title == null) {
            title = '';
        }

        $("#profile-view-title p").html(title);
    },
    showEditButtons: function(show) {
        if (show == null) {
            show = true;
        }

        if (show) {
            $("#edit_btn_group").show();
        }

        else {
            $("#edit_btn_group").hide();
        }
    },
    showAjaxLoadOverlay: function(show) {
        if (show) {
            $("#loader_overlay").fadeIn('fast');
        }

        else {
            $("#loader_overlay").fadeOut();
        }
    },
    image_upload_extra_param_callback: function(p) {
        var self = this;
        var member_id = member_view.getSelectedMemberId();
        var org_mem_id = member_view.getSelectedOrgMemberId();
        var params = {
            member_id: member_id,
            org_mem_id: org_mem_id
        };
        return params;
    },
    image_upload_callback: function(p) {
        //console.log(p);
        /*console.log(p['files']);
         console.log(p['files'][0]);
         return*/
        if (p != null) {
            var files = p['files'];
            var img_obg = files[0];
            if (typeof img_obg.error == 'undefined') {
                var img_url = img_obg.url;
                //console.log(img_url)
                $("#image-box").css('background-image', 'url(' + img_url + ')')
            }
        }
    },
    test: null

});
var member_view = null;
$(document).ready(function() {
    member_view = new MembersView();
});